const {
newsData,
list,
autoSort,
autoSort2,
save,
swiperData,
info,detail
} = require("../../api/index.js")
const utils = require('../../utils/index.js')
const menu = require('../../utils/menu.js')
// 去除Markdown符号，仅保留纯文本
function stripMarkdown(md) {
  if (!md) return '';
  return md.replace(/[\#\*\-\_\>\`]/g, '').replace(/\n+/g, ' ').trim();
}
Page({
data: {
value: null,
baseURL: wx.getStorageSync('baseURL') + "/",
    
homexiangmuchengguoList:[],
homexiangmuxinxiList:[],
isIndex: false,
forumArr: [],
newsList:[],
swiperList:[],
frontMenuList: [],
swiperUrl:"",
chengguofenleiList: [],
currentChengguoCategory: '全部',
latestNotice: null, // 最新公告
noticeScrollDuration: 15, // 滚动动画持续时间（秒）
navScrollLeft: 0,
navBarThumbLeft: 0,
},


onSwiperTap(e){

},
checkMoreTap(e) {
const tableName = e.currentTarget.dataset.tablename;
const tabar = getApp().globalData.tabarList;
wx.removeStorage({
key: 'isAuth',
})
if(tabar.includes(tableName)){
 wx.switchTab({
     url: `/pages/${tableName}/list`,
 })
}else{
 wx.navigateTo({
     url: `/pages/${tableName}/list`,
 })
}


},
async onLoad(options) {
    this.getData()
    // 初始化滑块位置
    this.setData({
      navBarThumbLeft: 0
    });
    },
async onShow() {
this.onLoad()
},
onSwiperTap(e){
const item= e.currentTarget.dataset.item
this.setData({
swiperUrl:item.url
})
},

    selectTap(e) {
        const item = e.currentTarget.dataset.item;
        // 如果是导师推荐，直接跳转（navigateTo）
        if (item.child[0].classname === 'daoshi') {
            wx.navigateTo({
                url: '/pages/daoshi/list'
            });
            return;
        }
        utils.menuTap(item.child[0].classname)
        this.setData({
            childItem: item.child
        })
    },
    cancelShow() {
        this.selectComponent('#bottomFrame').hideFrame();
    },
    menuTap(e) {
        const item = e.currentTarget.dataset.item;
                const tableName = item.child[0].classname;
                // 特殊处理“往期公告”
                if (tableName === 'gonggao') {
                    wx.navigateTo({
                        url: '/pages/news/list',
                    });
                    return;
                }
                utils.menuTap(tableName)

    },
    toNewsDetail(e) {
        const id = e.currentTarget.dataset.id;
        console.log("id", id);
        wx.navigateTo({
            url: `/pages/news/detail?id=${id}`,
        })
    },
    
    // 点击公告滚动文本跳转到详情
    toNoticeDetail(e) {
        const notice = e.currentTarget.dataset.notice;
        if (notice && notice.id) {
            wx.navigateTo({
                url: `/pages/news/detail?id=${notice.id}`,
            })
        }
    },
    toNewsList() {
        const tabar = getApp().globalData.tabarList
        if(tabar.includes('news')){
            wx.switchTab({
                url: `/pages/news/list`,
            })
        }else{
            wx.navigateTo({
                url: `/pages/news/list`,
            })
        }
    },
    async toDetail(e) {
        const item = e.currentTarget.dataset.item;
        const tablename = e.currentTarget.dataset.tablename;
        
        // 先触发触摸效果
        const { index, type } = e.currentTarget.dataset;
        if (type === 'chengguo') {
            const list = [...this.data.homexiangmuchengguoList];
            if (list[index]) {
                list[index].touchActive = true;
                this.setData({
                    homexiangmuchengguoList: list
                });
            }
        } else if (type === 'xinxi') {
            const list = [...this.data.homexiangmuxinxiList];
            if (list[index]) {
                list[index].touchActive = true;
                this.setData({
                    homexiangmuxinxiList: list
                });
            }
        }
        
        // 延迟跳转，让用户看到完整的触摸效果
        setTimeout(() => {
            getApp().globalData.detailId = item.id;
            getApp().globalData.detailList = item;
            wx.navigateTo({
                url: `/pages/${tablename}/detail`
            });
        }, 200); // 200ms延迟，确保效果完整展示
    },


    onSearch() {},

    onHide() {

    },

    onUnload() {

    },
    imageErrorHandler(e) {
        console.log('图片加载失败:', e)
        const { index, type } = e.currentTarget.dataset;
        
        // 为加载失败的图片添加错误样式类
        if (type === 'chengguo') {
            const list = this.data.homexiangmuchengguoList;
            if (list[index]) {
                list[index].imageError = true;
                this.setData({
                    homexiangmuchengguoList: list
                });
            }
        } else if (type === 'xinxi') {
            const list = this.data.homexiangmuxinxiList;
            if (list[index]) {
                list[index].imageError = true;
                this.setData({
                    homexiangmuxinxiList: list
                });
            }
        }
    },
    onPullDownRefresh() {

    },


    onReachBottom() {

    },
    onShareAppMessage() {
    },

    onChengguoCategoryTap(e) {
        const category = e.currentTarget.dataset.category;
        this.setData({
            currentChengguoCategory: category
        });
        // 可在此处添加筛选逻辑，如只显示该分类下的成果
    },

    async getData() {
 let baseURL=wx.getStorageSync("baseURL")+"/"
        this.setData({
            baseURL
        })
// 首页导航菜单自定义
const frontMenuList = [
  // 删除了表彰相关项
  {
    child: [
      {
        classname: 'xiangmuxinxi',
        menu: '项目库',
        img: '/static/images/xiangmuku.png',
        menuJump: '列表',
        tableName: 'xiangmuxinxi',
      }
    ],
    menu: '项目库',
  },
  {
    child: [
      {
        classname: 'daoshi',
        menu: '导师推荐',
        img: '/static/images/daoshituijian.png',
        menuJump: '列表',
        tableName: 'daoshi',
      }
    ],
    menu: '导师推荐',
  },
  {
    child: [
      {
        classname: 'aipersonal',
        menu: '电子档案',
        img: '/static/images/dianzidangan.png',
        menuJump: '列表',
        tableName: 'aipersonal',
      }
    ],
    menu: '电子档案',
  },
  {
    child: [
      {
        classname: 'xiangmuchengguo',
        menu: '项目成果',
        img: '/static/images/xiangmuchengguo.png',
        menuJump: '列表',
        tableName: 'xiangmuchengguo',
      }
    ],
    menu: '项目成果',
  },
  {
    child: [
      {
        classname: 'gonggao',
        menu: '往期公告',
        img: '/static/images/gonggao.png',
        menuJump: '列表',
        tableName: 'news',
      }
    ],
    menu: '往期公告',
  },
];
this.setData({
    frontMenuList
})



    const swiperRes = await swiperData(1, 5)
    const swiperList = swiperRes?.data?.list.filter(item=>(item.value)).map(item => {
            return {
                img: baseURL + item.value,
                title: item.name,
                id: item.id,
                ...item
            };
    })
    this.setData({
        swiperList
    })


const newsRes = await newsData(1, 6)
const newsList = newsRes?.data?.list.map(item => {
if (item) {
    item.addtime = item?.addtime.substring(0, 10);
}
return item;
});
this.setData({
newsList
})

// 获取最新公告用于滚动显示
if (newsList && newsList.length > 0) {
    const latestNotice = newsList[0];
    // 根据公告标题长度动态调整滚动时间
    const titleLength = latestNotice.title.length;
    const scrollDuration = Math.max(10, Math.min(20, titleLength * 0.5)); // 10-20秒之间
    
    this.setData({
        latestNotice: latestNotice,
        noticeScrollDuration: scrollDuration
    });
}

    const xiangmuchengguo = await list("xiangmuchengguo",
{
sfsh: "是",
page: 1,
                }


    )
    const xiangmuchengguoresult = xiangmuchengguo.data?.list?.map(item => {
    item.tupian = baseURL +
        item.tupian.split(",")[0];

        item.price = item?.price?.toFixed(2);
        item.vipprice = item?.vipprice?.toFixed(2);
        return item;
    });
    
    // 随机选择3个项目成果
    const randomChengguo = this.getRandomItems(xiangmuchengguoresult, 3);
    this.setData({
        homexiangmuchengguoList: randomChengguo
    })
    
    const xiangmuxinxi = await list("xiangmuxinxi",
{
sfsh: "是",
page: 1,
sort: 'tijiaoshijian',
order: "desc",
                }


    )
    const xiangmuxinxiresult = xiangmuxinxi.data?.list?.map(item => {
    item.xiangmutupian = baseURL +
        item.xiangmutupian.split(",")[0];

        item.price = item?.price?.toFixed(2);
        item.vipprice = item?.vipprice?.toFixed(2);
        // 处理项目简介，去除markdown，仅保留前50字
        item.xiangmujianjieShort = item.xiangmujianjie
          ? stripMarkdown(item.xiangmujianjie).slice(0, 50)
          : '';
        return item;
    });
    
    // 随机选择3个项目信息
    const randomXinxi = this.getRandomItems(xiangmuxinxiresult, 3);
    this.setData({
        homexiangmuxinxiList: randomXinxi
    })

    // 自动提取成果分类
    const chengguofenleiSet = new Set(["全部"]);
    xiangmuchengguoresult.forEach(item => {
        if (item.chengguofenlei) chengguofenleiSet.add(item.chengguofenlei);
    });
    this.setData({
        chengguofenleiList: Array.from(chengguofenleiSet)
    });

    },
    
    // 随机选择数组中的n个项目
    getRandomItems(array, n) {
        if (!array || array.length === 0) return [];
        if (array.length <= n) return array;
        
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        
        return shuffled.slice(0, n);
    },
    
    // 添加触摸开始事件处理
    onTouchStart(e) {
        try {
            const { index, type } = e.currentTarget.dataset;
            console.log('触摸开始:', index, type);
            
            if (type === 'chengguo') {
                const list = [...this.data.homexiangmuchengguoList];
                if (list[index]) {
                    list[index].touchActive = true;
                    this.setData({
                        homexiangmuchengguoList: list
                    });
                }
            } else if (type === 'xinxi') {
                const list = [...this.data.homexiangmuxinxiList];
                if (list[index]) {
                    list[index].touchActive = true;
                    this.setData({
                        homexiangmuxinxiList: list
                    });
                }
            }
        } catch (error) {
            console.error('触摸开始事件错误:', error);
        }
    },
    
    // 添加触摸结束事件处理
    onTouchEnd(e) {
        try {
            const { index, type } = e.currentTarget.dataset;
            console.log('触摸结束:', index, type);
            
            // 延迟移除触摸状态，与跳转延迟协调
            setTimeout(() => {
                if (type === 'chengguo') {
                    const list = [...this.data.homexiangmuchengguoList];
                    if (list[index]) {
                        list[index].touchActive = false;
                        this.setData({
                            homexiangmuchengguoList: list
                        });
                    }
                } else if (type === 'xinxi') {
                    const list = [...this.data.homexiangmuxinxiList];
                    if (list[index]) {
                        list[index].touchActive = false;
                        this.setData({
                            homexiangmuxinxiList: list
                        });
                    }
                }
            }, 250); // 250ms延迟，比跳转延迟稍长，确保效果完整展示
        } catch (error) {
            console.error('触摸结束事件错误:', error);
        }
    },
    onNavScroll(e) {
      // 横向滚动条同步滑块
      const scrollLeft = e.detail.scrollLeft;
      const scrollWidth = e.detail.scrollWidth;
      const navViewWidth = wx.getSystemInfoSync().windowWidth;
      const trackWidth = 60;
      const thumbWidth = 16;
      let percent = 0;
      if (scrollWidth > navViewWidth) {
        percent = scrollLeft / (scrollWidth - navViewWidth);
        percent = Math.max(0, Math.min(1, percent));
      }
      const maxLeft = trackWidth - thumbWidth;
      const thumbLeft = percent * maxLeft;
      this.setData({
        navBarThumbLeft: thumbLeft
      });
    }
})